package chap10collection.test9;


import java.util.HashSet;
import java.util.Set;

/**
 * @author zdl
 * @date 2024/12/17
 */
import java.util.*;

class Worker {
    String name;
    int age;
    //double salary; //改写为包装类
    Double salary;

    public Worker() {
    }

    public Worker(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    //hashCode()方法重写错误     salary是double类型  hashCode的返回值是int类型，因此应改写salary类型为Double包装类，然后使用包装类的hashCode方法
    /*int hashCode(){
        return name.hashCode() + age + salary;
    }*/

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Worker worker = (Worker) o;
        return age == worker.age && Objects.equals(name, worker.name) && Objects.equals(salary, worker.salary);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, salary);
    }
}

//自定义比较器
class MyComparator implements Comparator<Worker> {

    @Override
    public int compare(Worker o1, Worker o2) {
        if (o1.age - o2.age == 0) { //年龄相同 往下比较 工资
            if (o1.salary.compareTo(o2.salary) == 0) { //工资也相同  则按照名字排序
                return o1.name.compareTo(o2.name);
            }
            //年龄相同  但是工资不同，安装工资排序
            return o1.salary.compareTo(o2.salary);
        }
        //年龄不同 按照年龄排序
        return o1.age - o2.age;
    }
}

public class Demo9 {
    /**
     * 在前面的Demo8 Worker 类基础上，为 Worker 类添加相
     * 应的代码， 使得 Worker 对象能正确放入 TreeSet 中。并编写相应的测试代码。
     * 注：比较时，先比较工人年龄大小，年龄小的排在前面。如果两个工人年龄相同，
     * 则再比较其收入，收入少的排前面。如果年龄和收入都相同，则根据字典顺序比
     * 较工人姓名
     */
    public static void main(String[] args) {
        /*Set set = new HashSet();
        set.add(new Worker("“tom”", 18, 2000));
        set.add(new Worker("“tom”", 18, 2000));
        //set.add(0, new Worker("“jerry”", 18, 2000)); //HashSet 无序，不能使用下标
        System.out.println(set.size());  //1*/
        Set<Worker> set = new TreeSet<>(new MyComparator());
        set.add(new Worker("a", 18, 2000));
        set.add(new Worker("f", 18, 3000));
        set.add(new Worker("c", 13, 1900));
        set.add(new Worker("b", 18, 3000));
        for (Worker worker : set) {
            System.out.println(worker.name + "\t" + worker.age + "\t" + worker.salary + "\n");
        }

    }
}
